package com.andy.app_core.net.download;

import android.os.AsyncTask;

import com.andy.app_core.net.RestCreator;
import com.andy.app_core.net.callback.IError;
import com.andy.app_core.net.callback.IFailure;
import com.andy.app_core.net.callback.IRequest;
import com.andy.app_core.net.callback.ISuccess;

import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @version V1.0
 * @描述:
 * @Company:
 * @auth: Created by AN .
 * @time: 2020/3/26 21:38
 * @des
 */
public class DownloadHandler {
    private final HashMap<String,Object> PARAMS;
    private final String URL;
    private final IRequest REQUEST;
    private final ISuccess SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;
    //上传下载
    private final String DOWNLOAD_DIR;
    private final String EXTENSION;//扩展名
    private final String FILENAME;

    public DownloadHandler(HashMap<String, Object> PARAMS, String URL, IRequest REQUEST, ISuccess SUCCESS, IFailure FAILURE, IError ERROR, String DOWNLOAD_DIR, String EXTENSION, String FILENAME) {
        this.PARAMS = PARAMS;
        this.URL = URL;
        this.REQUEST = REQUEST;
        this.SUCCESS = SUCCESS;
        this.FAILURE = FAILURE;
        this.ERROR = ERROR;
        this.DOWNLOAD_DIR = DOWNLOAD_DIR;
        this.EXTENSION = EXTENSION;
        this.FILENAME = FILENAME;
    }

    public final void handleDownload(){
        RestCreator.getRestService().delete(URL,PARAMS).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if(response.isSuccessful()){
                    //开启异步下载操作
                    SaveFileTask task=new SaveFileTask(REQUEST,SUCCESS);
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,DOWNLOAD_DIR,EXTENSION,response.body(),FILENAME);

                    if(task.isCancelled()){
                        if(REQUEST != null){
                            REQUEST.onRequestEnd();
                        }
                    }
                }else{
                    if(ERROR != null){
                        ERROR.onError(response.code(),response.message());
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                if(FAILURE !=null){
                    FAILURE.onFailure();
                }
            }
        });
    }
}
